<?php
namespace Engine;
class Router
{
    protected $_routes = array('GET' => array(), 'POST' => array());
    
    public function addRoute($method, $route, $path, $paramsType = array())
    {
        // check method route
        if (!array_key_exists($method, $this->_routes)) {
            throw new \Exception('Method is not correct');
        }
        
        // set key params
        $keys = array();
        $uri_replace = trim($route, '/');
        $uri_replace = strtr($uri_replace, array(
            '/' => '\/',
            '.' => '\.'
        ));
        
        $uri_replace = preg_replace_callback('/\:[\w]+/', function($match) use(&$keys, $paramsType) {
            $paramName = trim($match[0], ':');
            if (!empty($paramsType) && isset($paramsType[$paramName])) {
                $keys[] = $paramName;
                return $paramsType[$paramName];
            }
            $keys[] = $paramName;
            return '\w+';
        }, $uri_replace);
        
        $this->_routes[$method][] = array(
            'uri' => $uri_replace,
            'path' => $path,
            'script_path' => strtr($path, array(APPLICATION_DIR . '/modules' => '', '.php' => '')),
            'params' => $keys
        );
    }
    
    public function getRoutes()
    {
        return $this->_routes;
    }
    
    public function match(\Engine\Request $request)
    {
        if (!array_key_exists($request->serverParam('REQUEST_METHOD'), $this->_routes)) {
        	throw new \Exception('Request method is not correct');
        }
        $uri = strtolower($request->getUri());
        
        $result = array();
        foreach ($this->_routes[$request->serverParam('REQUEST_METHOD')] as $route) {
        	if (preg_match('/^' . $route['uri'] . '$/i', $uri, $m)) {
        		unset($m[0]);
        		$params = array();
        		array_map(function($a, $b) use(&$params) {
        		 	$params[$a] = $b;
        		}, $route['params'], $m);
        		$request->setGetParams($params);
        		$result = $route;
        		break;
        	}
        }
        return $result;
    }
}